<template>
  <div id="app">
    <h1>美联储流动性实时指标面板</h1>
    <div class="input-section">
      <input
        v-model="apiKey"
        placeholder="输入你的 FRED API Key"
        @keyup.enter="loadCharts"
      />
      <button @click="loadCharts">加载数据</button>
    </div>

    <div v-if="loading" class="loading">📈 正在加载数据，请稍候...</div>

    <div v-for="series in seriesList" :key="series.id">
      <div v-if="chartData[series.id]" class="chart-container">
        <div class="chart-header">
          <h3 class="chart-title">{{ series.name }}</h3>
          <div class="chart-stats">
            <div class="latest-value">
              {{ chartData[series.id].latestValue.toLocaleString() }}
            </div>
            <div
              class="change-indicator"
              :class="chartData[series.id].changeClass"
            >
              {{ chartData[series.id].changeSymbol }}
              {{ Math.abs(chartData[series.id].change).toLocaleString() }}
              ({{ Math.abs(chartData[series.id].changePercent) }}%)
            </div>
          </div>
        </div>
        <canvas :ref="series.id"></canvas>
      </div>
      <div
        v-else-if="errors[series.id]"
        class="chart-container error"
      >
        ❌ 加载 {{ series.name }} 失败：{{ errors[series.id] }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

const API_KEY_STORAGE = 'fred_api_key'

export default {
  name: 'App',
  setup() {
    const apiKey = ref('')
    const loading = ref(false)
    const chartData = reactive({})
    const errors = reactive({})
    const chartInstances = {}

    const seriesList = [
      { id: 'RRPONTSYD', name: '逆回购使用量（MMRP）' },
      { id: 'RPONTSYD', name: '常设回购便利（SRF）' },
      { id: 'WRESBAL', name: '银行准备金余额' },
      { id: 'WTREGEN', name: '财政部账户余额（TGA）' },
      { id: 'SOFR', name: '隔夜担保利率（SOFR）' }
    ]

    const fetchFRED = async (series, key) => {
      const proxyUrl = `http://127.0.0.1:3000/fred?id=${series}&apiKey=${key}`
      const res = await fetch(proxyUrl)
      if (!res.ok) throw new Error('本地代理请求失败')
      const json = await res.json()
      const dates = json.observations.map((d) => d.date)
      const values = json.observations.map((d) => parseFloat(d.value))
      return { dates, values }
    }

    const loadCharts = async () => {
      if (!apiKey.value.trim()) {
        alert('请输入你的 FRED API Key')
        return
      }

      loading.value = true
      Object.keys(chartData).forEach((key) => delete chartData[key])
      Object.keys(errors).forEach((key) => delete errors[key])

      // 销毁旧的图表实例
      Object.values(chartInstances).forEach((chart) => {
        if (chart) chart.destroy()
      })

      for (const s of seriesList) {
        try {
          const { dates, values } = await fetchFRED(s.id, apiKey.value)

          // 计算最新值和变化
          const latestValue = values[values.length - 1]
          const previousValue = values[values.length - 2]
          const change = latestValue - previousValue
          const changePercent = ((change / previousValue) * 100).toFixed(2)

          // 确定变化方向和样式
          let changeClass = 'unchanged'
          let changeSymbol = ''
          if (change > 0) {
            changeClass = 'increase'
            changeSymbol = '↑'
          } else if (change < 0) {
            changeClass = 'decrease'
            changeSymbol = '↓'
          } else {
            changeSymbol = '—'
          }

          chartData[s.id] = {
            latestValue,
            change,
            changePercent,
            changeClass,
            changeSymbol
          }

          // 等待下一个tick以确保DOM已更新
          await new Promise((resolve) => setTimeout(resolve, 10))

          // 创建图表
          const canvas = document.querySelector(`canvas[data-v-inspector="${s.id}"]`) ||
                        Array.from(document.querySelectorAll('canvas')).find(c => 
                          c.parentElement?.parentElement?.querySelector('.chart-title')?.textContent === s.name
                        )
          
          if (canvas) {
            chartInstances[s.id] = new Chart(canvas, {
              type: 'line',
              data: {
                labels: dates.slice(-180),
                datasets: [
                  {
                    label: s.name,
                    data: values.slice(-180),
                    borderColor: '#38bdf8',
                    borderWidth: 2,
                    tension: 0.3,
                    fill: false
                  }
                ]
              },
              options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                  x: { ticks: { color: '#ccc' } },
                  y: { ticks: { color: '#ccc' } }
                },
                plugins: { legend: { labels: { color: '#fff' } } }
              }
            })
          }
        } catch (err) {
          errors[s.id] = err.message
        }
      }

      loading.value = false
      
      // 保存 API Key 到 localStorage
      localStorage.setItem(API_KEY_STORAGE, apiKey.value)
    }

    // 组件挂载时加载缓存的 API Key 并自动加载数据
    onMounted(() => {
      const cachedKey = localStorage.getItem(API_KEY_STORAGE)
      if (cachedKey) {
        apiKey.value = cachedKey
        // 自动加载数据
        loadCharts()
      }
    })

    return {
      apiKey,
      loading,
      chartData,
      errors,
      seriesList,
      loadCharts
    }
  }
}
</script>

